<template>
	<view class="content" v-if="deviceList.length">
		<view class="text-area">
			<view class="header-left">
				<view
					:class="selStatus === 0 ? 'active' : 'nomal'"
					@click="changeStatus(0, '', '')">
					<span>{{ t("index.search.0") }}</span>
					<span>·{{ total }}</span>
				</view>
				<span
					v-for="(item, index) in statusList"
					:key="index"
					:class="selStatus === index + 1 ? 'active' : 'nomal'"
					@click="changeStatus(index + 1, item.conn, item.work)">
					{{ item.name }}
				</span>
			</view>
			<view class="header-right">
				<up-avatar
					shape="square"
					size="24"
					@click="isTwo = !isTwo"
					:src="isTwo ? onePic : twoPic"></up-avatar>
				<view class="split">|</view>
				<up-avatar
					@click="clickSearh()"
					shape="square"
					size="24"
					src="/static/image/index/search.png"></up-avatar>
			</view>
		</view>
		<DeviceList
			:lastDeviceList="lastDeviceList"
			:toppedDevices="toppedDevices"
			:isTwo="isTwo"
			@updateTopList="updateTopList"
			@cancelAfter="cancelAfter"
			@updateDevicesTop="updateDeviceTop" />
		<view class="no-more" v-if="isLoadComplete">
			{{ t("noMore") }}
		</view>
	</view>
	<noDevice v-if="!deviceList.length" />
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, computed, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { onReachBottom, onPullDownRefresh } from "@dcloudio/uni-app";
import DeviceList from "./components/deviceList.vue";
import noDevice from "./components/noDevice.vue";
import { getBoundVcus } from "@/service/index";
import { useI18n } from "vue-i18n";
const { locale, t } = useI18n();
const instance: any = getCurrentInstance();
import type * as type from "./type";
const tokenStore = useUniversalStorage("token", "");
const isTwo = ref(true);
const total = ref(0);
const isLoading = ref(false);
const isLoadComplete = ref(false);
const deviceList = ref<type.Device[]>([]);
const toppedDevices = ref<string[]>([]);
const topDeviceList = ref<type.Device[]>([]);
const onePic = resolveStaticPath("image/index/one-column.png");
const twoPic = resolveStaticPath("image/index/two-column.png");
const bgc = resolveStaticPath("image/index/line.png");

const selStatus = ref(0); //全部、清扫、空闲、离线
const statusList = ref<type.Status[]>([
	{
		name: t("index.search.1"),
		conn: 1,
		work: 2,
	},
	{
		name: t("index.search.2"),
		conn: 1,
		work: 1,
	},
	{
		name: t("index.search.3"),
		conn: 1,
		work: "",
	},
]);
const params = ref<type.PaginationParams>({
	page: 1,
	size: 20,
	conn_stats: "",
	work_stats: "",
});

const lastDeviceList = computed<type.Device[]>(() => [
	...topDeviceList.value,
	...deviceList.value,
]);

const cancelAfter = (deviceSn: string) => {
	const deviceIndex = topDeviceList.value.findIndex(
		(dev) => dev.device_sn === deviceSn
	);
	const device = deviceIndex > -1 ? topDeviceList.value[deviceIndex] : null;
	if (deviceIndex > -1 && device) {
		topDeviceList.value.splice(deviceIndex, 1);
		deviceList.value.push(device);
	}
};

const updateTopList = (deviceSn: string) => {
	const deviceIndex = deviceList.value.findIndex(
		(dev) => dev.device_sn === deviceSn
	);
	if (deviceIndex > -1) {
		const newDeviceList = [...deviceList.value];
		const [topDevice] = newDeviceList.splice(deviceIndex, 1);
		deviceList.value = newDeviceList;
		topDeviceList.value = [topDevice, ...topDeviceList.value];
	}
};
const updateDeviceTop = (newToppedDevices: string) => {
	toppedDevices.value = newToppedDevices.split(",");
};
// 处理置顶设备
const handleTopDevices = (data: type.TopDeviceData) => {
	if (!data.top_devices || data.top_devices.length === 0) return;
	// 检查数据是否变化
	const isDataChanged =
		JSON.stringify(data.top_devices) !==
		JSON.stringify(topDeviceList.value);
	if (!isDataChanged) return;
	// 更新置顶设备索引
	toppedDevices.value = data.top_index ? data.top_index.split(",") : [];

	if (data.top_index) {
		// 按指定顺序排序
		const deviceMap = data.top_devices.reduce((map, device) => {
			map[device.device_sn] = device;
			return map;
		}, {} as Record<string, type.Device>);
		topDeviceList.value = toppedDevices.value
			.map((sn) => deviceMap[sn])
			.filter(Boolean);
	} else {
		// 无排序索引时直接使用原始数据
		topDeviceList.value = data.top_devices;
	}
};
const handleDevicesData = (data: type.Device[]) => {
	if (!data.devices || data.devices.length === 0) {
		isLoadComplete.value = true;
		return;
	}
	handleTopDevices(data);
	if (params.value.page === 1) {
		deviceList.value = [];
	}
	const filteredDevices = data.devices.filter(
		(device: type.Device[]) =>
			!toppedDevices.value.includes(device.device_sn)
	);
	deviceList.value = [...deviceList.value, ...filteredDevices];
	if (selStatus.value === 0) {
		total.value = data.total;
	}
};

const showLoading = () => {
	uni.showLoading({
		title: t("loading"),
		mask: true,
	});
};

const getDeviceList = async () => {
	if (params.value.page === 1) {
		showLoading();
	}
	try {
		uni.hideLoading();
		isLoading.value = true;
		const { data } = await getBoundVcus(params.value);
		if (data && !data.code) {
			handleDevicesData(data.data || []);
		} else {
			if (tokenStore.value) {
				instance?.proxy.$message(
					data?.msg || t("request.failed"),
					"warning"
				);
			}
		}
	} catch (error) {
		console.log(error);
		instance.proxy.$message(t("device.list.failed"), "error");
	} finally {
		uni.hideLoading();
		isLoading.value = false;
	}
};

// 重置查询
const resetparams = () => {
	params.value = {
		page: 1,
		size: 20,
		conn_stats: "",
		work_stats: "",
	};
	deviceList.value = [];
	isLoadComplete.value = false;
};
const changeStatus = (index: number, conn, work) => {
	if (selStatus.value === index) return;
	selStatus.value = index;
	params.value.conn_stats = conn;
	params.value.work_stats = work;
	getDeviceList();
};
const clickSearh = () => {
	uni.navigateTo({
		url: `/pages/index/search/index?toppedDevices=${toppedDevices.value.join()}`,
	});
};
// 上拉加载更多
onReachBottom(async () => {
	if (isLoading.value || isLoadComplete.value) return;
	try {
		params.value.page += 1;
		getDeviceList();
	} finally {
		isLoading.value = false;
	}
});
//下拉刷新
onPullDownRefresh(() => {
	setTimeout(() => {
		resetparams();
		getDeviceList();
		uni.stopPullDownRefresh();
	}, 1500);
});
onShow(() => {
	getDeviceList();
});
</script>

<style lang="scss" scoped>
.content {
	padding: 60rpx 30rpx;
	.text-area {
		display: flex;
		justify-content: space-between;
		padding: 4rpx 0;
		height: 24px;
		box-sizing: border-box;
	}
}

.header-left {
	display: flex;
	gap: 30rpx;
	vertical-align: text-bottom;
	.active {
		position: relative;
		vertical-align: text-bottom;
		font-size: 18px;
		font-weight: bold;
		color: #333333;
		padding-bottom: 10px;
	}
	.active::after {
		content: " ";
		display: inline-block;
		width: 16px;
		height: 3px;
		background: url("/static/image/index/line.png");
		background-size: 100% 100%;
		position: absolute;
		left: calc(50% - 8px);
		bottom: -10px;
	}
	.nomal {
		position: relative;
		color: #999999;
		font-size: 14px;
		vertical-align: text-bottom;
	}
}
.header-right {
	display: flex;
	.split {
		color: #e8e8e8;
		margin-left: 1px;
	}
}
.no-more {
	width: 100%;
	height: 25px;
	line-height: 25px;
	text-align: center;
	color: #999;
	margin-top: 20px;
	font-size: 14px;
}
</style>
